//
//  ChatInfoDao.m
//  SportSocial
//
//  Created by yull on 15/1/20.
//  Copyright (c) 2015年 yull. All rights reserved.
//

#import "ChatInfoDao.h"

@implementation ChatInfoDao

+ (instancetype)shareInstance
{
    static ChatInfoDao *infoDao = nil;
    static dispatch_once_t predicate;
    dispatch_once(&predicate, ^{
        infoDao = [[ChatInfoDao alloc] init];
    });
    return infoDao;
}

- (void)createTable
{
    [[DBManager shareInstance].dbQueue inDatabase:^(FMDatabase *db) {
        NSMutableArray *sqlArray = [NSMutableArray arrayWithObjects:
                                    @"CREATE TABLE IF NOT EXISTS chatInfo ("
                                    "[id] integer NOT NULL PRIMARY KEY AUTOINCREMENT, "
                                    "[privateId] integer,"
                                    "[groupId] integer,"
                                    "[name] varchar,"
                                    "[icon] varchar,"
                                    "[sex] integer,"
                                    "[content] varchar,"
                                    "[time] double,"
                                    "[unReadCount] integer,"
                                    "[senderName] varchar,"
                                    "[infoType] integer)"
                                    ,nil];

        [db beginTransaction];
        BOOL result = YES;
        for (NSString *sql in sqlArray) {
            result &= [db executeUpdate:sql];
        }
        if (result) {
            result &= [db commit];
        }
        
        if (!result) {
            [db rollback];
        }
    }];
}

- (BOOL)addOrUpdateChatInfo:(ChatInfo *)chatInfo
{
    BOOL isExist = [self checkIsExist:chatInfo];
    if (isExist) {
        return [self updateChatInfo:chatInfo];
    }else {
        return [self insertChatInfo:chatInfo];
    }
}

- (BOOL)checkIsExist:(ChatInfo *)chatInfo
{
    __block BOOL result = NO;
    
    [[DBManager shareInstance].dbQueue inDatabase:^(FMDatabase *db) {
        FMResultSet *resultSet = nil;
        if (chatInfo.infoType == ChatInfoTypePrivate) {
            resultSet = [db executeQuery:@"select * from chatInfo where privateId=?",[NSNumber numberWithLongLong:chatInfo.privateId]];
        }else {
            resultSet = [db executeQuery:@"select * from chatInfo where groupId=?",[NSNumber numberWithLongLong:chatInfo.groupId]];
        }
        
        if (resultSet.next) {
            result = YES;
            chatInfo.dbId = [resultSet longForColumn:@"id"];
            chatInfo.unReadCount += [resultSet intForColumn:@"unReadCount"];
        }
        [resultSet close];
    }];
    return result;
}

- (BOOL)updateChatInfo:(ChatInfo *)chatInfo
{
    __block BOOL result = NO;
    
    [[DBManager shareInstance].dbQueue inDatabase:^(FMDatabase *db) {
        result = [db executeUpdate:@"update chatInfo set name=?,icon=?,sex=?,content=?,time=?,unReadCount=?, senderName=?,infoType=? where id=?",
                  chatInfo.name,
                  chatInfo.icon,
                  [NSNumber numberWithInt:chatInfo.sex],
                  chatInfo.content,
                  [NSNumber numberWithDouble:chatInfo.time],
                  [NSNumber numberWithInteger:chatInfo.unReadCount],
                  chatInfo.senderName,
                  [NSNumber numberWithInteger:chatInfo.infoType],
                  [NSNumber numberWithLongLong:chatInfo.dbId]];
    }];
    return result;
}

- (BOOL)insertChatInfo:(ChatInfo *)chatInfo
{
    __block BOOL result = NO;
    
    [[DBManager shareInstance].dbQueue inDatabase:^(FMDatabase *db) {
        result = [db executeUpdate:@"insert into chatInfo (privateId,groupId,name,icon,sex,content,time,unReadCount,senderName,infoType) values(?,?,?,?,?,?,?,?,?,?)",
                  [NSNumber numberWithLongLong:chatInfo.privateId],
                  [NSNumber numberWithLongLong:chatInfo.groupId],
                  chatInfo.name,
                  chatInfo.icon,
                  [NSNumber numberWithInt:chatInfo.sex],
                  chatInfo.content,
                  [NSNumber numberWithDouble:chatInfo.time],
                  [NSNumber numberWithInteger:chatInfo.unReadCount],
                  chatInfo.senderName,
                  [NSNumber numberWithInteger:chatInfo.infoType]];
        if (result) {
            chatInfo.dbId = db.lastInsertRowId;
        }
    }];
    return result;
}

- (NSMutableArray *)selectAlChatInfo
{
    __block NSMutableArray *returnArray = [NSMutableArray array];
    
    [[DBManager shareInstance].dbQueue inDatabase:^(FMDatabase *db) {
        FMResultSet *resultSet = [db executeQuery:@"select * from chatInfo ORDER BY time DESC"];
        while (resultSet.next) {
            [returnArray addObject:[ChatInfo chatInfoWithResultSet:resultSet]];
        }
        [resultSet close];
    }];
    return returnArray;
}

#pragma mark - public
- (BOOL)addChatInfoArray:(NSArray *)array
{
    BOOL result = YES;
    for (ChatInfo *chatInfo in array) {
        result &= [self addOrUpdateChatInfo:chatInfo];
    }
    return result;
}

- (BOOL)clearUnReadCountWithChatInfo:(ChatInfo *)chatInfo
{
    __block BOOL ret = YES;
    [[DBManager shareInstance].dbQueue inDatabase:^(FMDatabase *db) {
        ret = [db executeUpdate:@"update chatInfo set unReadCount=0 where id=?",[NSNumber numberWithLongLong:chatInfo.dbId]];
    }];
    return ret;
}

- (BOOL)deleteChatInfo:(ChatInfo *)chatInfo
{
    __block BOOL ret = YES;
    [[DBManager shareInstance].dbQueue inDatabase:^(FMDatabase *db) {
        ret = [db executeUpdate:@"delete from chatInfo where id=?",[NSNumber numberWithLongLong:chatInfo.dbId]];
    }];
    return ret;
}
@end
